<!--OCR识别-->
<template>
  <span id="CameraOCR">
    <el-button @click="handleOpenDialog()">OCR识别</el-button>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :title="'OCR识别'"
      :modal-append-to-body="false"
      width="500px"
      custom-class="CameraUploadPhotoDialog">
      <el-radio-group v-model="type" style="margin-bottom:10px">
        <el-radio :label="1">身份证</el-radio>
        <el-radio :label="2">银行卡</el-radio>
        <el-radio :label="3">营业执照</el-radio>
        <el-radio :label="4">护照</el-radio>
        <el-radio :label="5">社保卡</el-radio>
      </el-radio-group>
      <div v-loading="videoLoading" class="read-sucess-tip tc" :element-loading-text="videoLoadingText">
        <div v-show="ocrFinish">
          <img :src="cameraImageSrc" style="border-radius: 8px;" :style="{width:width+'px',height:height+'px'}">
        </div>
        <div v-show="!ocrFinish">
          <video id="videoCamera" autoplay :width="width" :height="height" style="border-radius: 8px;" />
          <canvas id="canvasCamera" style="display:none;" :width="width" :height="height" />
        </div>
        <img v-if="showSuccessTip" class="success-tip" src="@/assets/images/cameraSuccess.png">
      </div>
      <div class="tip-div">请将相关材料贴近扫描设备</div>
      <div v-if="ocrFinish" class="ocrResult">
        <div class="title">识别结果：</div>
        <json-viewer
          :value="ocrResult!=null ? ocrResult:{} "
          :expand-depth="5"
          copyable
          sort />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="ocrFinish" @click="ocrFinish = false;showSuccessTip=false">重 拍</el-button>
        <el-button :disabled="ocrFinish" type="primary" @click="handlerPhoto">OCR识别</el-button>
        <el-button v-if="ocrFinish" type="primary" @click="handlerConfirm">确 定</el-button>

      </span>
    </el-dialog>
  </span>
</template>
<script>
import JsonViewer from 'vue-json-viewer'
export default {
  components: { JsonViewer },
  props: {
    width: {
      type: Number,
      required: false,
      default: 379
    },
    height: {
      type: Number,
      required: false,
      default: 238
    }
  },
  data() {
    return {
      cameraImageSrc: require('@/assets/images/cameraPhonto.png'),
      ocrFinish: false,
      dialogVisible: false,
      showSuccessTip: false, // 是否展示成功图标
      videoCamera: null,
      thisCancas: null,
      thisContext: null,
      videoLoadingText: '设备初始化中...',
      videoLoading: false,
      type: 1,
      ocrResult: {}

    }
  },
  watch: {
    type: function() {
      this.ocrFinish = false
      this.showSuccessTip = false
    }
  },
  mounted() {
  },
  methods: {
    hasGetUserMedia() {
      return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia)
    },
    getCompetence() {
      this.videoLoading = true
      this.videoLoadingText = '设备初始化中...'
      this.thisCancas = document.getElementById('canvasCamera')
      this.thisContext = this.thisCancas.getContext('2d')
      this.videoCamera = document.getElementById('videoCamera')
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {}
      }
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function(constraints) {
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
          if (!getUserMedia) {
            this.msgWarning()
            this.$notify({
              title: '警告',
              message: '当前浏览器版本太低，不支持媒体，建议升级至最新浏览器或使用谷歌浏览器',
              type: 'warning',
              duration: 0
            })
            this.videoLoading = false
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'))
          }
          return new Promise(function(resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject)
          })
        }
      }
      var constraints = { audio: false, video: { width: this.width, height: this.height, transform: 'scaleX(-1)' }}
      navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
        this.videoLoading = false
        if ('srcObject' in this.videoCamera) {
          this.videoCamera.srcObject = stream
        } else {
          this.videoCamera.src = window.URL.createObjectURL(stream)
        }
      }).catch(err => {
        console.log(err)
        this.$notify({
          title: '警告',
          message: '设备初始化失败：' + err,
          type: 'warning',
          duration: 0
        })
        this.videoLoading = false
      })
    },
    stopNavigator() {
      this.videoCamera.srcObject.getTracks()[0].stop()
    },
    handleClose(done) {
      this.$confirm('确认关闭？').then(_ => {
        done()
      }).catch(_ => {})
    },
    handleOpenDialog() {
      this.dialogVisible = true
      this.videoLoading = false
      this.showSuccessTip = false
      this.ocrFinish = false
      this.$nextTick(() => {
        this.getCompetence()
      })
    },
    handlerPhoto() {
      this.videoLoading = true
      this.videoLoadingText = '识别中...'
      this.thisContext.drawImage(this.videoCamera, 0, 0, this.width, this.height)
      this.$store.dispatch('ocrTool', {
        base64Image: this.thisCancas.toDataURL('image/png'),
        type: this.type
      }).then((res) => {
        this.ocrResult = res
        this.showSuccessTip = true
        this.videoLoading = false
        this.ocrFinish = true
        this.cameraImageSrc = this.thisCancas.toDataURL('image/png')
      }).catch((_) => {
        this.videoLoading = false
        this.ocrFinish = false
      })
    },
    handlerConfirm() {
      this.$emit('ocrResult', {
        ...this.ocrResult,
        type: this.type
      })
      this.dialogVisible = false
    }
  }
}
</script>
<style lang="scss" >
#CameraOCR{
  #IDPhoto{
    margin-bottom: 22px;
    .card-img{
      width: 182px;
      height: 114px;
      cursor: pointer;
    }
  }
  .el-radio{
    line-height: 30px;
  }
  .ocrResult{
    font-size: 14px;
    .title{
      font-size: 15px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .item{
      line-height: 30px;
    }
  }
  .el-dialog {
    margin-top: 18vh!important;
    border-radius: 10px;
    .tip-div {
      padding-top: 20px;
      margin: 0 auto;
      text-align: center;
      font-size: 18px;
      line-height: 26px;
      color: #303133;
    }
    .read-sucess-tip {
      position: relative;
    }
    .success-tip {
      position: absolute;
      left: 200px;
      top: 70px;
    }
  }
}
</style>
